function getRandomColor() {
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F06292', '#AEC6CF', '#F7DC6F'];
  return colors[Math.floor(Math.random() * colors.length)];
}


function createCollapsibleJsonViewer(rawJson) {
  const container = document.createElement('div');
  container.className = 'json-viewer';
  container.style.cssText = `
    font-family: monospace;
    font-size: 14px;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    margin: 20px auto;
    max-width: 90%;
  `;

  const header = document.createElement('div');
  header.style.cssText = `
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e0e0e0;
  `;

  const title = document.createElement('h2');
  title.textContent = 'JSON Viewer';
  title.style.cssText = 'margin: 0; font-size: 18px;';

  const controlsContainer = document.createElement('div');
  controlsContainer.style.cssText = 'display: flex; align-items: center; gap: 12px;';

  // Add copy button
  const copyButton = document.createElement('button');
  copyButton.style.cssText = `
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    position: relative;
    display: flex;
    align-items: center;
  `;

  // Add tooltip styles
  const style = document.createElement('style');
  style.textContent = `
    .tooltip {
      position: absolute;
      background: #000;
      color: white;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      bottom: 100%;
      left: 50%;
      transform: translateX(-50%);
      margin-bottom: 4px;
      white-space: nowrap;
      opacity: 0;
      visibility: hidden;
      transition: opacity 0.2s, visibility 0.2s;
    }
    .tooltip::after {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      transform: translateX(-50%);
      border-width: 4px;
      border-style: solid;
      border-color: #000 transparent transparent transparent;
    }
    .tooltip.show {
      opacity: 1;
      visibility: visible;
    }
  `;
  document.head.appendChild(style);

  // Create tooltip
  const tooltip = document.createElement('div');
  tooltip.className = 'tooltip';
  tooltip.textContent = 'Copy';
  copyButton.appendChild(tooltip);

  // Copy icon
  const copyIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  copyIcon.setAttribute('width', '16');
  copyIcon.setAttribute('height', '16');
  copyIcon.setAttribute('viewBox', '0 0 24 24');
  copyIcon.setAttribute('fill', 'none');
  copyIcon.setAttribute('stroke', 'currentColor');
  copyIcon.setAttribute('stroke-width', '2');
  copyIcon.innerHTML = `
    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
  `;
  copyButton.appendChild(copyIcon);

  // Check icon (hidden by default)
  const checkIcon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  checkIcon.setAttribute('width', '16');
  checkIcon.setAttribute('height', '16');
  checkIcon.setAttribute('viewBox', '0 0 24 24');
  checkIcon.setAttribute('fill', 'none');
  checkIcon.setAttribute('stroke', 'currentColor');
  checkIcon.setAttribute('stroke-width', '2');
  checkIcon.style.display = 'none';
  checkIcon.innerHTML = `
    <polyline points="20 6 9 17 4 12"></polyline>
  `;
  copyButton.appendChild(checkIcon);

  copyButton.addEventListener('mouseenter', () => {
    tooltip.classList.add('show');
  });

  copyButton.addEventListener('mouseleave', () => {
    tooltip.classList.remove('show');
  });

  copyButton.addEventListener('click', async () => {
    try {
      const contentToCopy = isRaw ? rawJson : JSON.stringify(JSON.parse(rawJson), null, 2);
      await navigator.clipboard.writeText(contentToCopy);
      
      // Show success state
      tooltip.textContent = 'Copied!';
      copyButton.style.color = '#4CAF50';
      copyIcon.style.display = 'none';
      checkIcon.style.display = 'block';
      
      // Reset after 2 seconds
      setTimeout(() => {
        tooltip.textContent = 'Copy';
        copyButton.style.color = 'inherit';
        copyIcon.style.display = 'block';
        checkIcon.style.display = 'none';
      }, 2000);
    } catch (err) {
      tooltip.textContent = 'Failed to copy';
      setTimeout(() => {
        tooltip.textContent = 'Copy';
      }, 2000);
    }
  });

  const toggleContainer = document.createElement('div');
  toggleContainer.style.cssText = 'display: flex; align-items: center; gap: 8px;';

  const toggleLabel = document.createElement('span');
  toggleLabel.textContent = '原生';
  toggleLabel.style.cssText = 'font-size: 14px;';

  const toggleSwitch = document.createElement('label');
  toggleSwitch.className = 'switch';
  toggleSwitch.style.cssText = `
    position: relative;
    display: inline-block;
    width: 40px;
    height: 20px;
  `;

  const toggleInput = document.createElement('input');
  toggleInput.type = 'checkbox';
  toggleInput.style.cssText = `
    opacity: 0;
    width: 0;
    height: 0;
  `;

  const toggleSlider = document.createElement('span');
  toggleSlider.className = 'slider';
  toggleSlider.style.cssText = `
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: .4s;
    border-radius: 10px;
  `;

  toggleSlider.innerHTML = '<span class="knob"></span>';
  const knobStyle = document.createElement('style');
  knobStyle.textContent = `
    .switch .slider .knob {
      position: absolute;
      content: "";
      height: 16px;
      width: 16px;
      left: 2px;
      bottom: 2px;
      background-color: white;
      transition: .4s;
      border-radius: 50%;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .switch input:checked + .slider {
      background-color: #ff9dd3 !important;
    }
    .switch input:checked + .slider .knob {
      transform: translateX(20px);
    }
  `;
  document.head.appendChild(knobStyle);

  toggleSwitch.appendChild(toggleInput);
  toggleSwitch.appendChild(toggleSlider);
  
  toggleContainer.appendChild(toggleLabel);
  toggleContainer.appendChild(toggleSwitch);

  controlsContainer.appendChild(copyButton);
  controlsContainer.appendChild(toggleContainer);

  header.appendChild(title);
  header.appendChild(controlsContainer);

  const content = document.createElement('div');
  container.appendChild(header);
  container.appendChild(content);

  let isRaw = false;
  let expandedPaths = new Set();
  let collapsedPaths = new Set();

  function toggleExpand(path, level) {
    if (level < 3) {
      if (collapsedPaths.has(path)) {
        collapsedPaths.delete(path);
      } else {
        collapsedPaths.add(path);
      }
    } else {
      if (expandedPaths.has(path)) {
        expandedPaths.delete(path);
      } else {
        expandedPaths.add(path);
      }
    }
    updateContent();
  }

  function renderValue(value, path, level = 0) {
    if (typeof value === 'object' && value !== null) {
      return renderObject(value, path, level);
    }
    if (typeof value === 'string') return `<span style="color: #4caf50;">"${escapeHtml(value)}"</span>`;
    if (typeof value === 'number') return `<span style="color: #2196f3;">${value}</span>`;
    if (typeof value === 'boolean') return `<span style="color: #ff9800;">${value}</span>`;
    if (value === null) return `<span style="color: #9e9e9e;">null</span>`;
    return String(value);
  }

  function renderObject(obj, path, level = 0) {
    const isExpanded = (level < 3 && !collapsedPaths.has(path)) || expandedPaths.has(path);
    const isArray = Array.isArray(obj);
    const bracketColor = getRandomColor();

    let html = `<div style="margin-left: 20px;">
      <span class="expander" data-path="${path}" data-level="${level}" style="cursor: pointer; user-select: none;">
        ${isExpanded ? '▼' : '▶'}
        <span style="color: ${bracketColor};">${isArray ? '[' : '{'}</span>
      </span>`;

    if (isExpanded) {
      html += '<div style="margin-left: 20px;">';
      Object.entries(obj).forEach(([key, value], index) => {
        html += '<div>';
        if (!isArray) {
          html += `<span style="color: #9c27b0;">"${escapeHtml(key)}"</span>: `;
        }
        html += renderValue(value, `${path}.${key}`, level + 1);
        if (index < Object.entries(obj).length - 1) {
          html += '<span style="color: #757575;">,</span>';
        }
        html += '</div>';
      });
      html += '</div>';
    } else {
      html += '<span>...</span>';
    }

    html += `<span style="color: ${bracketColor};">${isArray ? ']' : '}'}</span></div>`;
    return html;
  }

  function updateContent() {
    // console.log('Updating content. isRaw:', isRaw); // Debug log
    if (isRaw) {
      // console.log('Displaying raw JSON'); // Debug log
      const preElement = document.createElement('pre');
      preElement.style.cssText = 'white-space: pre-wrap; word-wrap: break-word; overflow-x: auto;';
      preElement.textContent = rawJson;
      content.innerHTML = '';
      content.appendChild(preElement);
    } else {
      // console.log('Displaying formatted JSON'); // Debug log
      try {
        const parsedJson = JSON.parse(rawJson);
        content.innerHTML = renderValue(parsedJson, 'root');
        content.querySelectorAll('.expander').forEach(el => {
          el.addEventListener('click', (e) => {
            e.stopPropagation();
            const path = el.dataset.path;
            const level = parseInt(el.dataset.level);
            toggleExpand(path, level);
          });
        });
      } catch (error) {
        content.innerHTML = `<pre style="color: red;">Error parsing JSON: ${escapeHtml(error.message)}</pre>`;
      }
    }
  }

  function escapeHtml(unsafe) {
    return unsafe
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  }

  toggleInput.addEventListener('change', () => {
    isRaw = toggleInput.checked;
    // console.log('Toggle changed. isRaw:', isRaw); // Debug log
    updateContent();
  });

  updateContent();
  return container;
}

function getRandomColor() {
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F06292', '#AEC6CF', '#F7DC6F'];
  return colors[Math.floor(Math.random() * colors.length)];
}

function injectJsonViewer(rawJson) {
  const viewer = createCollapsibleJsonViewer(rawJson);
  document.body.innerHTML = '';
  document.body.appendChild(viewer);
}

function handleJsonContent() {
  const rawJson = document.body.textContent || document.body.innerText;
  if (isJsonContent(rawJson)) {
    injectJsonViewer(rawJson);
  } else {
    console.error('Content is not valid JSON');
  }
}

function isJsonContent(content) {
  try {
    JSON.parse(content);
    return true;
  } catch (e) {
    return false;
  }
}

function checkAndFormatJson() {
  const contentType = document.contentType || '';
  if (contentType.includes('application/json') || (document.body && isJsonContent(document.body.textContent || document.body.innerText))) {
    handleJsonContent();
  } else {
    console.log('Not a JSON page'); // Debug log
  }
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', checkAndFormatJson);
} else {
  checkAndFormatJson();
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'format') {
    checkAndFormatJson();
  } else if (request.action === 'restore') {
    location.reload();
  }
  sendResponse({status: 'done'});
});
